#!/bin/bash

function process_arguments() {
    while [[ $# -gt 0 ]]
    do
      case "$1" in
        --debug|-d|--verbose|-v)
          echo "Running in debug/verbose mode"
          set -x
          shift
        ;;
        --silent)
          echo "Silent installation"
          SILENT=1
          shift
        ;;
        --install)
          echo "Base image creation"
          INSTALL=1
          shift
        ;;
        *)
          shift
        esac
    done
}

function install_repositories() {

  sudo apt-get -y -q update
  sudo apt-get -y -q install curl

  export os=debian
  export dist=bullseye 

  curl -s https://packagecloud.io/install/repositories/whitewaterfoundry/pengwin-base$1/script.deb.sh | sudo -E bash
  curl -s https://packagecloud.io/install/repositories/whitewaterfoundry/pengwin-setup$1/script.deb.sh | sudo -E bash
  curl -s https://packagecloud.io/install/repositories/whitewaterfoundry/wslu/script.deb.sh | sudo -E bash

  sudo apt-get update -y -q
}

function install_packages() {

  sudo apt-get -y -q install pengwin-base wslu pengwin-setup

  # Remove packagecloud repository definitions
  sudo rm /etc/apt/sources.list.d/whitewaterfoundry_*.list

  # Update apt repositories
  sudo apt-get -y -q update


  # Check for .dist-upgrade file in /etc/apt and inform user dist-upgrade available if so
  if [[ -f "/etc/apt/.dist-upgrade" ]] ; then
    sudo rm /etc/apt/.dist-upgrade
    sudo apt-get -y -q dist-upgrade
  fi

}

function remove_legacy_repo() {
  sudo sed -i -e 's|deb https://apt.patrickwu.space/ stable main|# deb https://apt.patrickwu.space/ stable main|g' /etc/apt/sources.list
  
}

function remove_legacy_regkeys() {
  bash /usr/local/pengwin-setup.d/explorer.sh --upgrade --yes

}

function invoke_setup() {
  sudo ln -s /usr/local/bin/pengwin-setup /etc/setup
  /usr/local/bin/pengwin-setup

}

function main() {

  process_arguments "$@"
  if [[ ! -f /usr/local/bin/pengwin-setup ]]; then

    local dev=""
    if [[ "$1" == "-dev" ]]; then

      dev="-dev"
    fi

    remove_legacy_repo
    install_repositories "${dev}"
    install_packages

    if [[ ! ${INSTALL} ]]; then
      remove_legacy_regkeys
    fi
  fi

  if [[ ! ${SILENT} ]]; then
    invoke_setup
  fi

}


main "$@"

exit 0
